package com.happymmall.controller.user;

import com.alibaba.fastjson.JSONObject;
import com.happymmall.entity.User;
import com.happymmall.service.UserService;
import com.happymmall.service.impl.UserServiceImpl;
import com.happymmall.util.Constants;
import com.happymmall.util.JwtUtils;
import com.happymmall.util.MD5Util;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;

@WebServlet("/user/register.do")
public class RegisterServlet extends HttpServlet {


    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 处理编码问题
        req.setCharacterEncoding("UTF-8");
        // 获取注册信息
        User user = new User();
        user.setUsername(req.getParameter("username"));
        user.setPassword(MD5Util.md5Encode(req.getParameter("password")));// md5加密
        user.setEmail(req.getParameter("email"));
        user.setPhone(req.getParameter("phone"));
        user.setQuestion(req.getParameter("question"));
        user.setAnswer(req.getParameter("answer"));

        UserService userService = new UserServiceImpl();
        int rs = userService.register(user);
        if (rs > 0) {

            //生成TOKEN
            Map<String, Object> claims = new HashMap<>();
            claims.put(Constants.USER_TOKEN, user.getId());
            String token = JwtUtils.generateToken(claims);

            resp.setContentType("application/json;charset=utf-8");
            Map<String, Object> resultData = new HashMap();
            resultData.put("status", 0);
            resultData.put("msg", "校验成功");

            JSONObject jsonObject = new JSONObject();
            String info = jsonObject.toJSONString(resultData);
            PrintWriter out = resp.getWriter();
            out.write(info);
        } else {
            resp.setContentType("application/json;charset=utf-8");
            Map<String, Object> resultData = new HashMap();
            resultData.put("status", 1);
            resultData.put("msg", "用户已存在");

            JSONObject jsonObject = new JSONObject();
            String info = jsonObject.toJSONString(resultData);
            PrintWriter out = resp.getWriter();
            out.write(info);
        }
    }
}
